package com.sgcc.nfc.lock.presentation.locks

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.sgcc.nfc.lock.R
import com.sgcc.nfc.lock.core.network.NetworkResult
import com.sgcc.nfc.lock.domain.model.Lock
import com.sgcc.nfc.lock.domain.usecase.DeleteLockUseCase
import com.sgcc.nfc.lock.domain.usecase.GetLocksUseCase
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

@HiltViewModel
class LocksViewModel @Inject constructor(
    private val getLocksUseCase: GetLocksUseCase,
    private val deleteLockUseCase: DeleteLockUseCase
) : ViewModel() {

    private val _locks = MutableLiveData<List<Lock>>(emptyList())
    val locks: LiveData<List<Lock>> = _locks

    private val _isLoading = MutableLiveData(false)
    val isLoading: LiveData<Boolean> = _isLoading

    private val _error = MutableLiveData<String?>()
    val error: LiveData<String?> = _error

    private val _message = MutableLiveData<Int?>()
    val message: LiveData<Int?> = _message

    private var searchJob: Job? = null
    private var currentKeyword: String? = null

    init {
        loadLocks()
    }

    fun loadLocks(keyword: String? = null) {
        currentKeyword = keyword
        viewModelScope.launch {
            _isLoading.value = true
            _error.value = null
            
            when (val result = getLocksUseCase(
                page = 1,
                pageSize = 100,
                keyword = keyword
            )) {
                is NetworkResult.Success -> {
                    _locks.value = result.data.data
                }
                is NetworkResult.Error -> {
                    _error.value = result.message
                }
                is NetworkResult.Loading -> {
                    // Loading state already set
                }
            }
            
            _isLoading.value = false
        }
    }

    fun search(keyword: String) {
        searchJob?.cancel()
        searchJob = viewModelScope.launch {
            delay(300) // 防抖动
            loadLocks(keyword.takeIf { it.isNotBlank() })
        }
    }

    fun deleteLock(lockId: Long) {
        viewModelScope.launch {
            _isLoading.value = true
            _error.value = null
            
            when (val result = deleteLockUseCase(lockId)) {
                is NetworkResult.Success -> {
                    _message.value = R.string.lock_delete_success
                    // 重新加载数据
                    loadLocks(currentKeyword)
                }
                is NetworkResult.Error -> {
                    _error.value = result.message ?: LOCK_DELETE_FAILED_FALLBACK
                }
                is NetworkResult.Loading -> {
                    // Loading state already set
                }
            }
            
            _isLoading.value = false
        }
    }

    fun clearMessage() {
        _message.value = null
    }

    fun clearError() {
        _error.value = null
    }

    companion object {
        private const val LOCK_DELETE_FAILED_FALLBACK = "删除锁具失败，请稍后再试"
    }
}


